package com.cochain.ftp;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.ssh.Sftp;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpException;
import org.apache.commons.net.ftp.FTPClient;

import java.io.File;
import java.util.Vector;

public class TestFtpClientPool {
    public static void main(String[] args) throws Exception{
//        // 笔者这里直接用main测试了
//        // (1)准备ftp配置
//        FtpProperties ftpProperties = FtpProperties.getFtpPropertiesA();
//        // (2)构造FtpClientFactory对象
//        FtpClientFactory ftpClientFactory = new FtpClientFactory(ftpProperties);
//        // (3)构造池对象
//        String flag = ftpProperties.getHost() + ":"+ ftpProperties.getPort();
//        FtpClientPool ftpClientPool = new FtpClientPool(ftpClientFactory,flag);
//
//        // 如果只是单池的话 ftpClientPool可以直接用了
//        // FTPClient ftpClient = ftpClientPool.borrowObject(); // 池获取连接
//        // ftpClientPool.returnObject(ftpClient); // 用完还连接
//
//        // (4)多ftp连接池构造
//        MultiFtpClientPoolFun<FtpClientPool> multiFtpClientPoolFun = new DefaultMultiFtpClientPool();
//        multiFtpClientPoolFun.initPool(flag,ftpClientPool);
//
//        // (5) 多ftp源获取连接   这个flag可以根据自己业务需求来定义
//        FtpClientPool pool = multiFtpClientPoolFun.getPool(flag);
//        FTPClient ftpClient = pool.borrowObject();
//        pool.returnObject(ftpClient);

        Sftp sftp = new Sftp("192.168.1.137",22,"root","cochain#123");
        downloadDir(sftp,"/usr/local/k8sAgent","/usr");

    }

    public static void downloadDir(Sftp sftp,String remotePath,String localPath) throws SftpException {

        ChannelSftp channelSftp = sftp.getClient();
        channelSftp.cd(remotePath);

        @SuppressWarnings("unchecked")
        Vector<ChannelSftp.LsEntry> fileList = channelSftp.ls(".");
        for (ChannelSftp.LsEntry file : fileList) {
            if (!".".equals(file.getFilename()) && !"..".equals(file.getFilename())) {
                String remoteFilePath = StrUtil.appendIfMissing(remotePath, "/") + file.getFilename();
                String localFilePath = StrUtil.appendIfMissing(localPath, "/") + file.getFilename();
                if (file.getAttrs().isDir()) {
                    File dir = new File(localFilePath);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    // 如果是文件夹，递归下载
                    downloadDir(sftp, remoteFilePath, localFilePath);
                } else {
                    File localFile = new File(localFilePath);
                    File parentFile = localFile.getParentFile();
                    if (!parentFile.exists()) {
                        parentFile.mkdirs();
                    }
                    // 如果是文件，直接下载
                    channelSftp.get(remoteFilePath, localFilePath);
                }
            }
        }
        sftp.close();
    }

}


